import { Watcher } from "./watcher";

export class Dep {
  subs: any;
  static target;
  constructor() {
    this.subs = []; /* 存放watcher */
  }
  /* 将当前Dep 存入watcher*/
  depend() {
    if (Dep.target) {
      Dep.target.addDep(this);
    }
  }
  //   遍历dep , 触发更新
  notify() {
    this.subs.sort((a, b) => {
      return a.id - b.id;
    });
    this.subs.forEach((watcher: any) => {
      watcher.update();
    });
  }
  /* 存放watcher到当前dep */
  addSub(watcher: Watcher) {
    if (!this.subs.includes(watcher)) {
      this.subs.push(watcher);
    }
  }
}

let stack = [];

export function pushTarget(watcher) {
  Dep.target = watcher;
  stack.push(watcher);
}
// 运行完之后清空当前的watcher
export function popTarget() {
  stack.pop();
  Dep.target = stack[stack.length - 1];
}
